package com.wisdytech.common.shiro;

import com.wisdytech.linkdcs.system.dao.ISysResourceDao;
import com.wisdytech.linkdcs.system.model.SysResource;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.system.service.ISystemResourceService;
import com.wisdytech.linkdcs.system.service.ISystemRoleService;
import com.wisdytech.linkdcs.system.service.IUserService;
import com.wisdytech.linkdcs.system.vo.ResourceNodeVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Component
public class MyShiroRealm extends CasRealm {

    private Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    @Value("${mes.url}")
    String mesUrl;

    @Resource
    private IUserService userService;

    @Resource
    private ISysResourceDao sysResourceDao;

    @Resource(name = "systemRoleService")
    private ISystemRoleService systemRoleService;

    @Resource
    private ISystemResourceService sysResourceService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

//              principals.getPrimaryPrincipal(); 这种方式也可以获取用户名
        String username = (String) super.getAvailablePrincipal(principals);
        logger.info(">>>>>>>>>>>>>>>>用户授权<<<<<<<<<<<<<<<<<<< ");
        Set<String> stringPermissions = new HashSet<>();
        List<SysResource> list = sysResourceDao.listResourceByUserName(username);
        for (SysResource sysResource:list) {
            Optional.ofNullable(sysResource).map(SysResource::getResCode).ifPresent(stringPermissions::add);
        }
        authorizationInfo.setStringPermissions(stringPermissions);
        return authorizationInfo;
    }

    //认证 登陆
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info(">>>>>>>>>>>>>>>>登陆认证<<<<<<<<<<<<<<<<<<< ");
        AuthenticationInfo authc = super.doGetAuthenticationInfo(token);
        if(authc == null) {
            return null;
        }
        // 获取登录的账号，cas认证成功后，会将账号存起来
        String username = (String) authc.getPrincipals().getPrimaryPrincipal();
        // 将用户信息存入session中,方便程序获取,此处可以将根据登录账号查询出的用户信息放到session中
        SysUser sysUser = userService.getSystemUserByName(username);
        SecurityUtils.getSubject().getSession().setAttribute("user", sysUser);

        //写入资源信息 多角色
        List<String> roleIds = systemRoleService.getRoleIdsByUserId(sysUser.getPkId());
        List<ResourceNodeVO> resources;
        if ("test1".equals(sysUser.getUsername()) || "test2".equals(sysUser.getUsername()) || "test3".equals(sysUser.getUsername())) {
            resources = sysResourceService.getSuperAdminResources();
        } else {
            resources = sysResourceService.getRoleResources(roleIds);
        }
        SecurityUtils.getSubject().getSession().setAttribute("resources", resources);
        SecurityUtils.getSubject().getSession().setAttribute("mesUrl", mesUrl);
        return authc;
    }

}
